/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/lite/kernels/internal/reference/leaky_relu.h"

#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/quantization_util.h"
#include "tensorflow/lite/kernels/internal/reference/process_broadcast_shapes.h"
#include "tensorflow/lite/kernels/internal/types.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/micro/kernels/kernel_util.h"

#include "cmsis/CMSIS/Core/Include/cmsis_compiler.h"
#include <math.h>

namespace tflite {
namespace {

// Input/output tensor index.
constexpr int kInputTensor = 0;
constexpr int kOutputTensor = 0;

struct RsLeakyReluOpData {
  // quantization parameters
	int32_t iz1, iz2;
	float s1, s2, z1, z2; // input scale, output scale, input zeropt, output zeropt
	// input >=0: (a-z1)*s1=(x-z2)*s2 => 	x = a * (s1/s2)  + (z2 - z1 *  s1/s2) = a * w + b
	// input < 0: (a-z1)*as1 = (x-z2)*s2 => x = a * (as1/s2) + (z2 - z1 * as1/s2) = a * aw + ab
	float w, b, aw, ab;
};

TfLiteStatus CalculateOpData(TfLiteContext* context, TfLiteNode* node) {
  TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
  const TfLiteTensor* input;
  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
  TfLiteTensor* output;
  TF_LITE_ENSURE_OK(context,
                    GetOutputSafe(context, node, kOutputTensor, &output));
  TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);

  if (output->type == kTfLiteInt8) {
    RsLeakyReluOpData* data = static_cast<RsLeakyReluOpData*>(node->user_data);
    const auto* params =
        static_cast<TfLiteLeakyReluParams*>(node->builtin_data);

    data->iz1 = input->params.zero_point;
    data->iz2 = output->params.zero_point;
	data->z1 = data->iz1;
	data->z2 = data->iz2;
	data->s1 = input->params.scale;
	data->s2 = output->params.scale;
	
	data->w = data->s1 / data->s2;
	data->aw = data->w * params->alpha;
	data->b = data->z2 - data->z1 * data->w;
	data->ab = data->z2 - data->z1 * data->aw;
  }

  return kTfLiteOk;
}

void RsLeakyReLUCalc(const int8_t *p1, int8_t *p2, size_t cnt, RsLeakyReluOpData *pCfg) {
	size_t i;
	// a: input value, int8
	// x: LeakyReLU(a), int8
	// s1: input scaler
	// z1: input zero point
	// s2: output scaler
	// z2: output zero point
	// as1: s1 * alpha
	// w = s1/s2
	// b = z2 - z1 * s1/s2
	// aw = alpha * s1/s2
	// ab = z2 - z1 * alpha * s1/s2
	// input >=0: (a-z1)*s1=(x-z2)*s2 => 	x = a * (s1/s2)  + (z2 - z1 *  s1/s2) = a * w + b
	// input < 0: (a-z1)*as1 = (x-z2)*s2 => x = a * (as1/s2) + (z2 - z1 * as1/s2) = a * aw + ab	
	// a * w + b => single VMLA.F32 instruction on Cortex-M cores with FPU
	int32_t a, x;
	float f32X;
	int32_t iz1 = pCfg->iz1, iz2 = pCfg->iz2;
	float w = pCfg->w, aw = pCfg->aw, b = pCfg->b, ab = pCfg->ab;
	
	#ifdef RKRELU_UNROLL_LOOP
	while (cnt > 1)
	{
		a = *p1++;
		if (a - iz1 >= 0) {
			f32X = (float)a * w + b;
		} else {
			f32X = (float)a * aw + ab;
		}
		x = roundf(f32X);
		x = __SSAT(x, 8);
		*p2++ = x;
		
		a = *p1++;
		if (a - iz1 >= 0) {
			f32X = (float)a * w + b;
		} else {
			f32X = (float)a * aw + ab;
		}
		x = roundf(f32X);
		x = __SSAT(x, 8);
		*p2++ = x;
		cnt -= 2;
	}
	#endif
	while(cnt--) {
		a = *p1++;
		if (a - iz1 >= 0) {
			f32X = (float)a * w + b;
		} else {
			f32X = (float)a * aw + ab;
		}
		x = roundf(f32X);
		x = __SSAT(x, 8);
		*p2++ = x;
	}
}

void* LeakyReluInit(TfLiteContext* context, const char* buffer, size_t length) {
  TFLITE_DCHECK(context->AllocatePersistentBuffer != nullptr);
  return context->AllocatePersistentBuffer(context, sizeof(RsLeakyReluOpData));
}

TfLiteStatus LeakyReluPrepare(TfLiteContext* context, TfLiteNode* node) {
  return CalculateOpData(context, node);
}

TfLiteStatus LeakyReluEval(TfLiteContext* context, TfLiteNode* node) {
  const TfLiteEvalTensor* input =
      tflite::micro::GetEvalInput(context, node, kInputTensor);
  TfLiteEvalTensor* output =
      tflite::micro::GetEvalOutput(context, node, kOutputTensor);
  const RsLeakyReluOpData& data = *static_cast<RsLeakyReluOpData*>(node->user_data);

  switch (input->type) {
    case kTfLiteFloat32: {
      LeakyReluParams op_params = {};
      const auto* params =
          static_cast<TfLiteLeakyReluParams*>(node->builtin_data);

      op_params.alpha = params->alpha;
      reference_ops::LeakyRelu(op_params, tflite::micro::GetTensorShape(input),
                               tflite::micro::GetTensorData<float>(input),
                               tflite::micro::GetTensorShape(output),
                               tflite::micro::GetTensorData<float>(output));
      return kTfLiteOk;
    } break;
    case kTfLiteInt8: {
		RsLeakyReLUCalc(
		tflite::micro::GetTensorData<int8_t>(input), 
		tflite::micro::GetTensorData<int8_t>(output), 
		NumElements(input->dims), 
		static_cast<RsLeakyReluOpData*>(node->user_data)
		);
      return kTfLiteOk;
    } break;
    default:
      TF_LITE_KERNEL_LOG(
          context, "Only float32, int8 are supported by LEAKY_RELU, got %s.",
          TfLiteTypeGetName(input->type));
      return kTfLiteError;
  }

  return kTfLiteError;
}

}  // namespace

TfLiteRegistration Register_LEAKY_RELU() {
  return {/*init=*/LeakyReluInit,
          /*free=*/nullptr,
          /*prepare=*/LeakyReluPrepare,
          /*invoke=*/LeakyReluEval,
          /*profiling_string=*/nullptr,
          /*builtin_code=*/0,
          /*custom_name=*/nullptr,
          /*version=*/0};
}

}  // namespace tflite
